/*
 * @Description:
 * @Author: HYH
 * @LastEditors: HYH
 * @LastEditTime: 2022-12-28 16:29:56
 */

/**
 *
 * @param src 图片地址
 */
export const useFile = () => {
  /**通过 canvas */
  const byCanvas = (src: string) => {
    const image = new Image()
    image.src = src
    image.onload = function () {
      const { width, height, src } = image
      const canvas = document.createElement('canvas')
      canvas.width = width
      canvas.height = height
      const ctx = canvas.getContext('2d')
      /**扩展名 */
      const ext = src.substring(src.lastIndexOf('.') + 1).toLowerCase()
      ctx!.drawImage(image, 0, 0, width, height)
      const dataURL = canvas.toDataURL('image/' + ext)
      return dataURL
    }
  }

  /**通过 blob */
  const byBlob = async (src: string) => {
    const b = await fetch(src)
    const blob = await b.blob()
    const file = new File([blob], 'test.png')
    const a = document.createElement('a')
    a.setAttribute('download', file.name)
    a.href = URL.createObjectURL(file)
    a.click()
  }

  return { byCanvas, byBlob }
}
